package com.starbaba.spread.view;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.RandomUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.db.Short_Link;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.redis.JedisUtils;
import com.starbaba.spread.model.DataVO;
import com.starbaba.spread.model.ShortLinkAddisusedModel;
import com.starbaba.spread.model.SpreadChannelModel;
import com.starbaba.spread.service.SpreadService;
import com.starbaba.tools.sequence.IntUtil;
import com.starbaba.tools.sequence.Sequence;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class SpreadAction extends BaseAction implements ModelDriven {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1629639856220872834L;

	private SpreadChannelModel model;

	private SpreadService service;

	private InputStream input;

	private String fileName;

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	public SpreadAction() {
		logCategorysArrayList = new ArrayList<ControlLogCategory>();
	}

	public String getFileName() {
		return fileName;
	}

	public String showPage() {
		paramsMap.put("userId", userVO.getUserid());
		return "success";
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public String updateIsUsed(){
		//获取到参数
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		System.out.println(paramsMap);
		//对获取的参数进行封装构造
		ShortLinkAddisusedModel slmodel = new ShortLinkAddisusedModel();
		parsePageRequest();
		try {
			slmodel=service.queryShortLinkAddisusedModel(String.valueOf(paramsMap.get("id")));
		} catch (Exception e) {
			LogService.error("查询异常");
		}
		service.update(slmodel);
		JedisUtils.del(LoanRedisKey.SHORT_LINK_REDIRECT + slmodel.getShort_link());
		return "success";
	}

	public void queryAllSpreadData() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		System.out.println(paramsMap);
		model.setType(null);
		String channel = (String) paramsMap.get("channel");
		model.setChannel(channel);
		parsePageRequest();
		try {
			PageResponse pageResponse = new PageResponse();
			List list = service.getDataList(pageRequest.getIDisplayStart(), pageRequest.getIDisplayLength(), model,
					pageResponse, getService());
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			String jsonStr = JsonUtils.toJson(pageResponse, null, true, null, false);
			sendJsonMessage(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void querySpreadData() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// 操作类别：0为全部订单，1未完成订单，2为成功订单，3为失败订单
		String type = (String) paramsMap.get("channelId");
		model.setType(Long.valueOf(type));

		parsePageRequest();
		try {
			PageResponse pageResponse = new PageResponse();
			List list = service.getDataList(pageRequest.getIDisplayStart(), pageRequest.getIDisplayLength(), model,
					pageResponse, getService());
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			String jsonStr = JsonUtils.toJson(pageResponse, null, true, null, false);
			sendJsonMessage(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String addRecord() {
		paramsMap.put("channelList", model.getChannelList());
		return "success";
	}

	@LogAble(operate = LogAble.OPERATE_ADD)
	public void addRecordRequest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// 操作类别：0为全部订单，1未完成订单，2为成功订单，3为失败订单
		String channel = (String) paramsMap.get("channel");
		Long channel1 = Long.valueOf(channel).longValue();
		String cost = (String) paramsMap.get("cost");
		String time = (String) paramsMap.get("costtime");
		String wznum = (String) paramsMap.get("wznum");
		Long id = Sequence.getSequence();
		LogService.debug(cost + "_" + channel + "_" + time);

		parsePageRequest();
		try {
			DataVO entity = new DataVO();
			entity.setChannel(channel1);
			entity.setCount(Integer.valueOf(cost));
			entity.setId(id);
			entity.setWznum(Integer.valueOf(wznum));

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			Date date = null;
			try {
				date = sdf.parse(time);
				entity.setDate(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			Object ret = this.getService().doCreate(DataVO.class, entity);
			if (null == ret) {
				sendErrMsg("新增失败");
			} else {
				JsonObject result = new JsonObject();
				ResultJson resultJs = new ResultJson();
				resultJs.msg = "添加成功";
				result.add("result", resultJs.toJSON());

				sendJsonMessage(result.toString());

				ControlLogCategory logCategory = new ControlLogCategory();
				logCategory.setId(String.valueOf(id));
				logCategory.setName(channel);
				logCategorysArrayList.add(logCategory);
			}
		} catch (Exception e) {
			sendErrMsg(e.getMessage());
		}
	}

	public InputStream getInputStream() {
		return input;
	}

	public String editRecord() {
		paramsMap.put("channelList", model.getChannelList());
		return "success";
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void editRecordRequest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// 操作类别：0为全部订单，1未完成订单，2为成功订单，3为失败订单
		String channel = (String) paramsMap.get("channel");
		String cost = (String) paramsMap.get("cost");
		String sourceid = (String) paramsMap.get("sourceid");

		System.out.println(channel + "_" + cost + "_" + sourceid);

		parsePageRequest();
		try {

			DataVO entity = new DataVO();
			entity.setId(Long.valueOf(sourceid));

			List<?> list = this.getService().doFindByProperty(DataVO.class, "id", Long.valueOf(sourceid));
			if (null != list && list.size() > 0) {
				DataVO v = (DataVO) list.get(0);
				entity.setDate(v.getDate());
				entity.setChannel(Long.valueOf(channel));
				entity.setCount(Integer.valueOf(cost));
				this.getService().doUpdate(DataVO.class, entity);
			}

			JsonObject result = new JsonObject();
			result.add("result", new ResultJson().toJSON());
			sendJsonMessage(result.toString());

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(sourceid);
			logCategory.setName(channel);
			logCategorysArrayList.add(logCategory);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void queryShortLink() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String memo = (String) paramsMap.get("memo");
		String activity = (String)paramsMap.get("activity");
		String shortLink = (String) paramsMap.get("shortLink");
		if (null != memo) {
			model.setMemo(memo);
			model.setActivity(activity);
			model.setShortLink(shortLink);
		}
		parsePageRequest();
		try {
			PageResponse pageResponse = new PageResponse();
			List list = service.getShortLink(pageRequest.getIDisplayStart(), pageRequest.getIDisplayLength(), model,
					pageResponse, getService());
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			String jsonStr = JsonUtils.toJson(pageResponse, null, true, null, false);
			sendJsonMessage(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	@LogAble(operate = LogAble.OPERATE_ADD, actionId = "1000000503")
	public void addShortLinkRequest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// 操作类别：0为全部订单，1未完成订单，2为成功订单，3为失败订单
		String soruceurl = (String) paramsMap.get("soruceurl");
		String memo = (String) paramsMap.get("memo");
		String unit_price  = (String) paramsMap.get("unit_price");
		String link_type = (String) paramsMap.get("link_type");
		String activity = (String) paramsMap.get("activity");
		String environment = (String) paramsMap.get("environment");
		parsePageRequest();
		try {
			BaseDao dao = new BaseDao(Constant.POOL_LIFE);

			ShortLinkAddisusedModel link = new ShortLinkAddisusedModel();
			Long id = Sequence.getSequence();
			link.setId(id);
			link.setMemo(memo);
			link.setUrl(soruceurl);
			link.setCtime(new Date());
			link.setLink_type(link_type);
			link.setUnit_price(Float.parseFloat(unit_price));
			link.setActivity(activity);
			String slink = RandomUtils.getRandomMixString(new Random().nextInt(2) + 4);
			link.setShort_link(slink);
			link.setEnvironment(Integer.parseInt(environment));
			
			dao.add(link);
			
			String sourceResult = JSONUtils.toJsonString(link);
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "添加成功:" + Constant.COMMON_HOST + "/share_service/redirect?from=" + slink;
			result.add("result", resultJs.toJSON());

			//String key = "redict_" + slink;
			String key = LoanRedisKey.SHORT_LINK_REDIRECT + slink;
			JedisUtils.set(key, sourceResult);
			
//			ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
//			list.add(new BasicNameValuePair("key", key));
//			list.add(new BasicNameValuePair("value", sourceResult));
//			String connection = HttpConnectionUtils.connection(Constant.COMMON_HOST + "/mredis/oper/set",
//					HttpConnectionUtils.POST, list);
			
			service.setNginxName(memo, slink);
			sendJsonMessage(result.toString());

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(String.valueOf(id));
			logCategory.setName(memo);
			logCategorysArrayList.add(logCategory);

		} catch (Exception e) {
			LogService.error(e);
			sendErrMsg(e.getMessage());
		}
	}

	/**
	 * 展示短链重定向链接修改弹框
	 * @return
	 */
	public String showUpdateRedirectLinkDialog(){
		String appLink = JedisUtils.get(LoanRedisKey.SHORT_LINK_APP_REDIRECT_LINK);
		String outerLink = JedisUtils.get(LoanRedisKey.SHORT_LINK_OUTER_REDIRECT_LINK);
		paramsMap.put("appLink", appLink);
		paramsMap.put("outerLink", outerLink);
		return "success";
	}

	/**
	 * 修改重定向链接
	 */
	@LogAble(operate = LogAble.OPERATE_ADD)
	public void updateRedirectLinkRequest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String appLink = (String) paramsMap.get("appLink");
		String outerLink = (String) paramsMap.get("outerLink");
		parsePageRequest();
		try {

			LogService.info("用户：" + userVO.getUserid() + " 将app内部跳转链接修改为：" + appLink + " 原链接为：" + JedisUtils.get(LoanRedisKey.SHORT_LINK_APP_REDIRECT_LINK));
			LogService.info("用户：" + userVO.getUserid() + " 将app外部跳转链接修改为：" + outerLink + " 原链接为：" + JedisUtils.get(LoanRedisKey.SHORT_LINK_OUTER_REDIRECT_LINK));

			if(StringUtils.isBlank(appLink)){
				JedisUtils.del(LoanRedisKey.SHORT_LINK_APP_REDIRECT_LINK);
			}else{
				JedisUtils.set(LoanRedisKey.SHORT_LINK_APP_REDIRECT_LINK, appLink);
			}

			if(StringUtils.isBlank(outerLink)){
				JedisUtils.del(LoanRedisKey.SHORT_LINK_OUTER_REDIRECT_LINK);
			}else{
				JedisUtils.set(LoanRedisKey.SHORT_LINK_OUTER_REDIRECT_LINK, outerLink);
			}

			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "修改成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());

		} catch (Exception e) {
			LogService.error(e);
			sendErrMsg(e.getMessage());
		}
	}

	@LogAble(operate = LogAble.OPERATE_ADD, actionId = "1000000503")
	public void addShortLint() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

		String url = (String) paramsMap.get("url");
		String memo = (String) paramsMap.get("memo");

		Long id = Sequence.getSequence();
		Short_Link link = new Short_Link();
		link.setId(id);
		link.setUrl(url);
		link.setCtime(new Date());
		link.setMemo(memo);

		String shortlint = IntUtil.couponGen(id, 5);
		link.setShort_link(shortlint);

		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		try {
			dao.add(link);

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(String.valueOf(id));
			logCategory.setName(memo);
			logCategorysArrayList.add(logCategory);

		} catch (AppException e) {
			e.printStackTrace();
		}
	}

	@LogAble(operate = LogAble.OPERATE_DEL)
	public void delRecord() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

		String sourceid = (String) paramsMap.get("sourceid");

		parsePageRequest();
		try {
			DataVO entity = new DataVO();
			entity.setId(Long.valueOf(sourceid));

			this.getService().doRemoveByVO(DataVO.class, entity);

			JsonObject result = new JsonObject();
			result.add("result", new ResultJson().toJSON());
			sendJsonMessage(result.toString());

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(sourceid);
			logCategory.setName("");
			logCategorysArrayList.add(logCategory);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Autowired
	@Qualifier("spreadServiceImpl")
	public void setImageService(SpreadService carAmercementService) {
		this.service = carAmercementService;
	}

	@Override
	public Object getModel() {
		if (model == null) {
			model = new SpreadChannelModel();
		}
		return model;
	}

	public String getActionId() {
		return "001302";
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

	private void sendErrMsg(String msg) {
		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = msg;
		result.add("result", resultJs.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println(RandomUtils.getRandomMixString(4));
	}

}
